﻿var AuthenticationPage = function(pageContainer) {

    var self = this;

    AuthenticationPage.superclass.constructor.call(this, pageContainer);

    this.IsExitPoint = true;

    var Elements = {
        username: pageContainer.find("#username"),
        password: pageContainer.find("#password"),
        authenticateButton: pageContainer.find("#authenticateButton"),
        usernameInfo: pageContainer.find('.usernameInfo'),
        language: pageContainer.find('.language-select')
    };

    this.authenticate = function(username, password) {
        Elements.username.val(username);
        Elements.password.val(password);
        authenticateUser();
    };

    this.initialize = override(self.initialize, function() {
        app.translatePage(app.Pages.Authentication);

        Elements.authenticateButton.click(function(e) {
            authenticateUser();
            return Event.stopEvent(e);
        });

        Elements.usernameInfo.click(function() {
            app.MessagesFactory.showDialog(translate('General_Explanation'), translate('Authentication_Username_Explanation'), [
                {
                    Text: translate('General_Ok'),
                    Callback: function() {
                        app.MessagesFactory.hideDialog();
                    }
                }
            ]);
            return false;
        });

        Elements.username.keyup(function(e) {
            if (e.keyCode == Keys.ENTER) {
                authenticateUser();
                Elements.username.blur();
            }
            Event.stopEvent(e);
        });

        Elements.password.keyup(function(e) {
            if (e.keyCode == Keys.ENTER) {
                authenticateUser();
                Elements.password.blur();
            }
            Event.stopEvent(e);
        });

        pageContainer.bind('onBeforePageShow', function() {
            if (app.LeftMenu.instance)
                app.LeftMenu.instance.hide();

            app.Phone.hideMenu();
            app.TMMService.Security.resetServerUrl();
            app.TMMService.Security.resetToken();
        });

        Elements.language.val(app.User.Settings.Language.substr(0, 2));

        loadLastConnectedUser();
        app.Phone.getConnectionData();
    });

    var loadLastConnectedUser = function() {
        var lastUser = $.jStorage.get("lastUser");
        if (lastUser)
            Elements.username.val(lastUser.Username);
    };

    var getServerAndUsername = function() {
        var u = Elements.username.val();
        if (!u)
            return null;

        var username = "";
        var server = "";

        var pos = u.indexOf("\\");
        if (pos >= 0) {
            server = u.substr(0, pos);
            username = u.substr(pos + 1);
        } else {
            var defaultServer = $("[id*='DefaultServerHF']").val() || "";

            server = defaultServer;
            username = u;
        }

        return {
            Username: username,
            Server: server
        };
    };

    var authenticateUser = function() {
        var credentials = getServerAndUsername();

        var username = credentials ? credentials.Username : null;
        if (!username)
            return app.MessagesFactory.showToastWarning(translate('Authentication_Warning'), translate('Authentication_UsernameError'));

        var password = Elements.password.val();
        if (!password)
            return app.MessagesFactory.showToastWarning(translate('Authentication_Warning'), translate('Authentication_PasswordError'));

        var server = credentials.Server;

        app.showLoadingScreen();
        app.TMMService.Redirect.GetConnectionUrl(server, function(response) {
            if (!response || !response.ServiceAddress) {
                app.hideLoadingScreen();
                app.MessagesFactory.showError(translate('Authentication_CodServerIncorect'));
                return;
            }

            if (location.href.toLowerCase().indexOf(response.ApplicationUrl.toLowerCase()) < 0) {
                app.Phone.loadApplication(server, username, password);
                return;
            }

            getAvailableCompanies(server, username, password, response.IsSAAS);
        });
    };

    var getAvailableCompanies = function(server, username, password, isSAAS) {
        var authData = {
            username: username,
            password: password,
            server: server,
            isSAAS: isSAAS,
            liso: Elements.language.val()
        };

        callGetAvailableCompaniesService(server, username, password, isSAAS, function(response) {
            app.hideLoadingScreen();
            if (response.Exception)
                return app.MessagesFactory.showError(translate('Authentication_Failed'));

            if (isSAAS)
                response.FinalResult = response;

            if (!response.FinalResult || !response.FinalResult.length) {
                app.MessagesFactory.showError(translate('Authentication_FaraAccess'));
                return;
            }

            app.Phone.setServer(server);

            if (isSAAS) {
                var companies = new Array();
                for (var i = 0; i < response.FinalResult.length; i++)
                    companies.push({
                        Id: response.FinalResult[i].Id,
                        Nume: response.FinalResult[i].Name
                    });

                response.FinalResult = companies;
            }

            if (!app.Pages.CompanyConnection.instance)
                app.Pages.CompanyConnection.instance = new CompanyConnectionPage(app.Pages.CompanyConnection.container, response.FinalResult, authData);
            else {
                app.Pages.CompanyConnection.instance.AuthData = authData;
                app.Pages.CompanyConnection.instance.initialize();
            }

            app.changePage(app.Pages.CompanyConnection);
        });
    };

    var callGetAvailableCompaniesService = function(server, username, password, isSAAS, callback) {
        if (isSAAS)
            app.TMMService.Redirect.GetAvailableCompanies(server, username, password, Constants.defaultLanguage, callback);
        else app.TMMService.Security.GetAvailableCompanies(server, username, password, callback);
    };

    this.goBack = function() {
        if (app.MessagesFactory.isDialogVisible())
            return app.MessagesFactory.hideDialog();
        if (app.Phone)
            app.Phone.exitApplication();
    };

    self.initialize();
};
extend(AuthenticationPage, TMMobilePage);